package com.geekstudy.week6.annotation;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.Properties;

import com.geekstudy.week6.source.MapConfigSource;
import org.apache.commons.lang.StringUtils;
import org.eclipse.microprofile.config.spi.ConfigSource;

public class DefaultConfigSourceFactory implements ConfigSourceFactory {

    @Override
    public ConfigSource createConfigSource(String name, int ordinal, URL resource, String encoding) {
        ConfigSource configSource = null;
        try (InputStream inputStream = resource.openStream();
             InputStreamReader reader = new InputStreamReader(inputStream, encoding)) {
            Properties properties = new Properties();
            properties.load(reader);
            String actualName = StringUtils.isBlank(name) ? resource.toString() : name;
            configSource = new MapConfigSource(actualName, ordinal, properties);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return configSource;
    }


}
